{% extends 'base/base.html' %}
{% load static %}

{% block title %}合作超市 - 妙趣拾光锦盒{% endblock %}

{% block extra_css %}
<style>
    .market-card {
        border-radius: 15px;
        overflow: hidden;
        transition: all 0.3s ease;
        height: 100%;
    }
    
    .market-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
    }
    
    .market-image {
        height: 180px;
        object-fit: cover;
    }
    
    .rating-stars {
        color: #ffc107;
    }
    
    .market-badge {
        position: absolute;
        top: 10px;
        right: 10px;
        padding: 5px 10px;
        font-weight: 600;
        font-size: 0.8rem;
    }
    
    .filter-section {
        background-color: #f8f9fa;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 30px;
    }
    
    .filter-button {
        margin-right: 10px;
        margin-bottom: 10px;
        border-radius: 20px;
        font-weight: 500;
        padding: 8px 15px;
    }
    
    .map-btn {
        border-radius: 30px;
        font-weight: 500;
        padding: 8px 20px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1>合作超市</h1>
        <div>
            <a href="{% url 'market:map' %}" class="btn btn-outline-primary map-btn">
                <i class="fas fa-map-marked-alt me-2"></i>查看地图
            </a>
            <a href="{% url 'market:apply' %}" class="btn btn-primary map-btn">
                <i class="fas fa-handshake me-2"></i>申请合作
            </a>
        </div>
    </div>
    
    <!-- 筛选区域 -->
    <div class="filter-section mb-4">
        <div class="row">
            <div class="col-md-6">
                <h5 class="mb-3">评分筛选</h5>
                <div>
                    <a href="{% url 'market:list' %}{% if sort and sort != 'rating' %}?sort={{ sort }}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}{% endif %}" 
                       class="btn {% if not rating_filter %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        全部评分
                    </a>
                    <a href="{% url 'market:list' %}?rating=4.5{% if sort and sort != 'rating' %}&sort={{ sort }}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}{% endif %}" 
                       class="btn {% if rating_filter == '4.5' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        4.5分以上
                    </a>
                    <a href="{% url 'market:list' %}?rating=4.0{% if sort and sort != 'rating' %}&sort={{ sort }}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}{% endif %}" 
                       class="btn {% if rating_filter == '4.0' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        4.0分以上
                    </a>
                    <a href="{% url 'market:list' %}?rating=3.5{% if sort and sort != 'rating' %}&sort={{ sort }}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}{% endif %}" 
                       class="btn {% if rating_filter == '3.5' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        3.5分以上
                    </a>
                </div>
            </div>
            <div class="col-md-6">
                <h5 class="mb-3">排序方式</h5>
                <div>
                    <a href="{% url 'market:list' %}{% if rating_filter and rating_filter != 'None' %}?rating={{ rating_filter }}{% endif %}" 
                       class="btn {% if not sort or sort == 'rating' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        按评分排序
                    </a>
                    <a href="#" id="distanceSortBtn"
                       class="btn {% if sort == 'distance' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        按距离排序
                    </a>
                    <a href="{% url 'market:list' %}?sort=box_count{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}" 
                       class="btn {% if sort == 'box_count' %}btn-primary{% else %}btn-outline-primary{% endif %} filter-button">
                        按盲盒数量排序
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 超市列表 -->
    <div class="row">
        {% for market in markets %}
        <div class="col-md-4 mb-4">
            <div class="card market-card border-0 shadow-sm">
                <div class="position-relative">
                    <img src="{{ market.image_url|default:'/static/images/default-market.jpg' }}" class="card-img-top market-image" alt="{{ market.name }}">
                    <span class="badge bg-primary market-badge">
                        {{ market.box_count }} 个盲盒
                    </span>
                </div>
                <div class="card-body">
                    <h5 class="card-title">{{ market.name }}</h5>
                    <div class="rating-stars mb-2">
                        {% for i in '12345'|make_list %}
                            {% if forloop.counter <= market.rating %}
                            <i class="fas fa-star"></i>
                            {% else %}
                            <i class="far fa-star"></i>
                            {% endif %}
                        {% endfor %}
                        <span class="ms-1 text-muted">({{ market.rating }})</span>
                    </div>
                    <p class="card-text text-muted small mb-3">
                        <i class="fas fa-map-marker-alt me-1"></i> {{ market.address }}
                    </p>
                    <p class="card-text text-muted small mb-3">
                        <i class="fas fa-clock me-1"></i> {{ market.business_hours|default:"工作时间待定" }}
                    </p>
                    <div class="d-grid">
                        <a href="{% url 'market:detail' market_id=market.market_id %}" class="btn btn-primary">查看详情</a>
                    </div>
                </div>
            </div>
        </div>
        {% empty %}
        <div class="col-12 text-center py-5">
            <div class="mb-4">
                <i class="fas fa-store-alt-slash" style="font-size: 4rem; color: #6c757d;"></i>
            </div>
            <h3>暂无符合条件的超市</h3>
            <p class="text-muted">请尝试调整筛选条件或稍后再来查看</p>
            <a href="{% url 'market:list' %}" class="btn btn-primary mt-3">
                <i class="fas fa-redo me-2"></i>查看全部超市
            </a>
        </div>
        {% endfor %}
    </div>
    
    <!-- 分页 -->
    {% if markets.paginator.num_pages > 1 %}
    <div class="d-flex justify-content-center mt-4">
        <nav aria-label="Page navigation">
            <ul class="pagination">
                {% if markets.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page=1{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}{% if sort %}&sort={{ sort }}{% endif %}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}" aria-label="First">
                        <span aria-hidden="true">&laquo;&laquo;</span>
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ markets.previous_page_number }}{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}{% if sort %}&sort={{ sort }}{% endif %}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                {% endif %}
                
                {% for num in markets.paginator.page_range %}
                    {% if num == markets.number %}
                    <li class="page-item active">
                        <span class="page-link">{{ num }}</span>
                    </li>
                    {% elif num > markets.number|add:"-3" and num < markets.number|add:"3" %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ num }}{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}{% if sort %}&sort={{ sort }}{% endif %}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}">{{ num }}</a>
                    </li>
                    {% endif %}
                {% endfor %}
                
                {% if markets.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ markets.next_page_number }}{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}{% if sort %}&sort={{ sort }}{% endif %}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page={{ markets.paginator.num_pages }}{% if rating_filter and rating_filter != 'None' %}&rating={{ rating_filter }}{% endif %}{% if sort %}&sort={{ sort }}{% endif %}{% if sort == 'distance' and request.GET.lat and request.GET.lng %}&lat={{ request.GET.lat }}&lng={{ request.GET.lng }}{% endif %}" aria-label="Last">
                        <span aria-hidden="true">&raquo;&raquo;</span>
                    </a>
                </li>
                {% endif %}
            </ul>
        </nav>
    </div>
    {% endif %}
    
    <!-- 获取附近超市 -->
    <div class="card mt-5 border-0 shadow-sm rounded-3">
        <div class="card-body p-4">
            <h3 class="card-title mb-4">查找附近超市</h3>
            <p class="card-text text-muted mb-4">允许获取您的位置信息，我们将为您查找附近的合作超市</p>
            <button id="getNearbyMarketsBtn" class="btn btn-primary">
                <i class="fas fa-location-arrow me-2"></i>获取附近超市
            </button>
            
            <div id="nearbyMarketsContainer" class="mt-4 d-none">
                <h5>附近的超市</h5>
                <div id="nearbyMarketsList" class="list-group mt-3">
                    <!-- 这里将动态显示附近超市列表 -->
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const getNearbyBtn = document.getElementById('getNearbyMarketsBtn');
        const nearbyContainer = document.getElementById('nearbyMarketsContainer');
        const nearbyList = document.getElementById('nearbyMarketsList');
        const distanceSortBtn = document.getElementById('distanceSortBtn');
        
        // 处理距离排序按钮点击
        if (distanceSortBtn) {
            distanceSortBtn.addEventListener('click', function(e) {
                e.preventDefault();
                
                // 检查是否支持地理位置
                if (!navigator.geolocation) {
                    alert('您的浏览器不支持地理定位功能，无法按距离排序');
                    return;
                }
                
                // 获取位置并跳转
                navigator.geolocation.getCurrentPosition(function(position) {
                    const lat = position.coords.latitude;
                    const lng = position.coords.longitude;
                    
                    // 构建URL并跳转
                    let url = `{% url 'market:list' %}?sort=distance&lat=${lat}&lng=${lng}`;
                    if ('{{ rating_filter }}' && '{{ rating_filter }}' !== 'None') {
                        url += `&rating={{ rating_filter }}`;
                    }
                    window.location.href = url;
                }, function(error) {
                    // 处理错误
                    let errorMsg = '获取位置失败，无法按距离排序: ';
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMsg = '需要获取您的位置才能按距离排序，请允许位置访问';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMsg += '位置信息不可用';
                            break;
                        case error.TIMEOUT:
                            errorMsg += '请求超时';
                            break;
                        case error.UNKNOWN_ERROR:
                            errorMsg += '未知错误';
                            break;
                    }
                    alert(errorMsg);
                });
            });
        }
        
        if (getNearbyBtn) {
            getNearbyBtn.addEventListener('click', function() {
                // 检查是否支持地理位置
                if (!navigator.geolocation) {
                    alert('您的浏览器不支持地理定位功能');
                    return;
                }
                
                // 获取位置
                navigator.geolocation.getCurrentPosition(function(position) {
                    const lat = position.coords.latitude;
                    const lng = position.coords.longitude;
                    
                    // 显示加载中
                    nearbyContainer.classList.remove('d-none');
                    nearbyList.innerHTML = '<div class="text-center py-3"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">正在查找附近超市...</p></div>';
                    
                    // 发送请求
                    fetch(`/market/nearest/?lat=${lat}&lng=${lng}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                nearbyList.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
                                return;
                            }
                            
                            if (data.markets && data.markets.length > 0) {
                                let html = '';
                                data.markets.forEach(market => {
                                    html += `
                                        <a href="/market/detail/${market.market_id}/" class="list-group-item list-group-item-action">
                                            <div class="d-flex w-100 justify-content-between">
                                                <h5 class="mb-1">${market.name}</h5>
                                                <small>${market.distance.toFixed(2)} 公里</small>
                                            </div>
                                            <p class="mb-1">${market.address}</p>
                                            <div class="d-flex align-items-center">
                                                <div class="rating-stars me-2">
                                                    ${getRatingStars(market.rating)}
                                                </div>
                                                <small class="text-muted">${market.business_hours || '营业时间待定'}</small>
                                            </div>
                                        </a>
                                    `;
                                });
                                nearbyList.innerHTML = html;
                            } else {
                                nearbyList.innerHTML = '<div class="alert alert-info">附近没有找到合作超市</div>';
                            }
                        })
                        .catch(error => {
                            nearbyList.innerHTML = `<div class="alert alert-danger">查询失败: ${error.message}</div>`;
                        });
                }, function(error) {
                    // 处理错误
                    let errorMsg = '获取位置失败: ';
                    switch(error.code) {
                        case error.PERMISSION_DENIED:
                            errorMsg += '用户拒绝了位置请求';
                            break;
                        case error.POSITION_UNAVAILABLE:
                            errorMsg += '位置信息不可用';
                            break;
                        case error.TIMEOUT:
                            errorMsg += '请求超时';
                            break;
                        case error.UNKNOWN_ERROR:
                            errorMsg += '未知错误';
                            break;
                    }
                    
                    nearbyContainer.classList.remove('d-none');
                    nearbyList.innerHTML = `<div class="alert alert-danger">${errorMsg}</div>`;
                });
            });
        }
        
        // 辅助函数：生成星级评分HTML
        function getRatingStars(rating) {
            let starsHtml = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= rating) {
                    starsHtml += '<i class="fas fa-star" style="color: #ffc107;"></i>';
                } else {
                    starsHtml += '<i class="far fa-star" style="color: #ffc107;"></i>';
                }
            }
            return starsHtml;
        }
    });
</script>
{% endblock %} 